package com.badibadi.slide;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.nio.charset.Charset;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;

import com.badibadi.activity.BaseActivity;
import com.badibadi.activity.ChatActivity;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.IOUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class music_select extends BaseActivity implements OnClickListener {

	private Button Pick_music;
	private TextView textview3;
	private ImageView Music_icon, Upload;
	private static final int MUSIC_PICKED = 3;

	static String fileName = "";
	static String fileNamePath = "";
	private String actId;

	// 服务器上接收文件的处理页面，这里根据需要换成自己的
	// private String url = "http://192.168.10.102/test.php";
	private String url = Constants.BadiUrl_1 + "Index/toUploadAmr";
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {
					Utils.ExitPrgress_Noclose(music_select.this);
					Utils.showMessage(music_select.this, getResources()
							.getString(R.string.l_net_error));
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;
			case 5:
				try {
					Utils.ExitPrgress_Noclose(music_select.this);
					String path = msg.getData().getString("msg");
					Toast.makeText(getApplicationContext(), "", 0).show();
					Intent it = new Intent();
					it.putExtra("slide_path", path);
					setResult(300, it);
					music_select.this.finish();
				} catch (Exception e) {
					// TODO: handle exception
				}
				break;

			default:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.main2);
		actId = getIntent().getStringExtra("actId");

		Music_icon = (ImageView) findViewById(R.id.imageView1);

		textview3 = (TextView) findViewById(R.id.textview3);

		Pick_music = (Button) findViewById(R.id.button2);
		Pick_music.setOnClickListener(this);

		/* 设置Upload的onClick事件处理 */
		Upload = (ImageView) findViewById(R.id.imageView2);
		Upload.setOnClickListener(this);

	}

	public void onClick(View view) {
		switch (view.getId()) {

		case R.id.button2:

			Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
			innerIntent.setType("audio/*");

			Intent wrapperIntent = Intent.createChooser(innerIntent, null);
			startActivityForResult(wrapperIntent, MUSIC_PICKED);

			break;

		case R.id.imageView2:

			if ((null != fileName && !fileName.equals(""))
					&& (null != fileNamePath && !fileNamePath.equals(""))) {

				// new FileUploadAsyncTask().execute(new File(fileNamePath));
				File file = new File(fileNamePath);
//				   ("DIERCI=" + file.getPath());

				if (file.exists()) {
					UpSound(file);
				} else {
				}
			} else {
				Toast.makeText(getApplicationContext(), "請先選取音樂",
						Toast.LENGTH_SHORT).show();

			}

			break;

		}
	}

	// 上传已经录制好的语音
	public void UpSound(File path) {
		Utils.showPrgress_Noclose(music_select.this);
		AjaxParams params = new AjaxParams();
		// File file = new File(path);
		if (path.exists()) {
		}
		try {
			params.put("info", path);
			if (actId != null) {
				params.put("aid", actId);
			}
			params.put("chat", "0");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			   
		}
		FinalHttp fh = new FinalHttp();
		// fh.configTimeout(15000);
		// fh.configRequestExecutionRetryCount(3);
		fh.post(Constants.BadiUrl_1 + "Index/toUploadAmr", params,
				new AjaxCallBack<Object>() {
					Message message;
					Bundle bundle;

					@Override
					public void onLoading(long count, long current) {
						// TODO Auto-generated method stub
						super.onLoading(count, current);
						// message = new Message();
						// bundle = new Bundle();
						// message.what = 6;
						// bundle.putInt("msg", (int) count);
						// message.setData(bundle);
						// handler.sendMessage(message);
					}

					@Override
					public void onSuccess(Object t) {
						// TODO Auto-generated method stub
						// Utils.ExitProgress_hen(context);
//						if (t != null) {
//						}

						Results results = Utils.checkResult_NNN(
								music_select.this, (String) t);
						if (results != null
								&& !results.getRetmsg().equals("null")
								&& results.isRet() == true) {
							message = new Message();
							bundle = new Bundle();
							message.what = 5;
							bundle.putString("msg", results.getRetmsg());
							message.setData(bundle);
							handler.sendMessage(message);
						} else {
							handler.sendEmptyMessage(1);
						}
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) {
			return;
		} else {
			String mCustomRingtone = null;
			if (requestCode == MUSIC_PICKED) {
				Uri pickedUri = data.getData();
				if (pickedUri != null) {
					mCustomRingtone = pickedUri.toString();
					ContentResolver cr = this.getContentResolver();
					Cursor cursor = cr.query(pickedUri, null, null, null, null);
					cursor.moveToFirst();

					// fileNamePath音樂來源路徑
					// fileName 音樂名稱

					fileNamePath = cursor
							.getString(cursor
									.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
					fileName = cursor
							.getString(cursor
									.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));

					textview3.setText(fileName);
					cursor.close();

				} else {
					textview3.setText("null:");
				}
			}
		}

		Upload.setVisibility(View.VISIBLE);
		Music_icon.setVisibility(View.GONE);
	}

	// class FileUploadAsyncTask extends AsyncTask<File, Integer, String> {
	// private ProgressDialog pd;
	// private long totalSize;
	//
	// protected void onPreExecute() {
	// pd = new ProgressDialog(music_select.this);
	// pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	// pd.setMessage("上传中....");
	// pd.setCancelable(false);
	// // pd.show();
	// }
	//
	// protected String doInBackground(File... params) {
	// // 保存需上传文件信息
	// MultipartEntityBuilder entitys = MultipartEntityBuilder.create();
	// entitys.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
	// entitys.setCharset(Charset.forName(HTTP.UTF_8));
	//
	// File file = params[0];
	// entitys.setBoundary("----WebKitFormBoundaryx2nqzr0UjNgDDf3v");
	// entitys.addPart("info", new FileBody(file));
	// entitys.addTextBody("aid", actId);
	// entitys.addTextBody("chat", "0");
	// HttpEntity httpEntity = entitys.build();
	// totalSize = httpEntity.getContentLength();
	// ProgressOutHttpEntity progressHttpEntity = new ProgressOutHttpEntity(
	// httpEntity, new ProgressListener() {
	// @Override
	// public void transferred(long transferedBytes) {
	// publishProgress((int) (100 * transferedBytes / totalSize));
	// }
	// });
	// return uploadFile(url, progressHttpEntity);
	// }
	//
	// protected void onProgressUpdate(Integer... progress) {
	// pd.setProgress((int) (progress[0]));
	// }
	//
	// protected void onPostExecute(String result) {
	// pd.dismiss();
	// Toast.makeText(music_select.this, result, Toast.LENGTH_SHORT)
	// .show();
	// }

	// /**
	// * 上传文件到服务器
	// *
	// * @param url
	// * 服务器地址
	// * @param entity
	// * 文件
	// * @return
	// */
	// public String uploadFile(String url, ProgressOutHttpEntity entity) {
	// HttpClient httpClient = new DefaultHttpClient();
	// httpClient.getParams().setParameter(
	// CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
	// // 设置连接超时时间
	// httpClient.getParams().setParameter(
	// CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
	// HttpPost httpPost = new HttpPost(url);
	// httpPost.setHeader("Content-Type",
	// "multipart/form-data;boundary=----WebKitFormBoundaryx2nqzr0UjNgDDf3v");
	// httpPost.setEntity(entity);
	// try {
	// HttpResponse httpResponse = httpClient.execute(httpPost);
	// if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
	// return "文件上传成功";
	// }
	// } catch (ClientProtocolException e) {
	//    
	// } catch (ConnectTimeoutException e) {
	//    
	// } catch (Exception e) {
	//    
	// } finally {
	// if (httpClient != null
	// && httpClient.getConnectionManager() != null) {
	// httpClient.getConnectionManager().shutdown();
	// }
	// }
	// return "文件上传失败";
	// }
	// }
}
